<template>
  <div class="app-container">
    <el-form
      :model="form"
      label-width="80px"
    >
      <el-form-item :label="$t('server')">
        <el-select v-model="serverId">
          <el-option
            v-for="item in serverList"
            :key="item.serverId"
            :label="item.name"
            :value="item.serverId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('device')+$t('name')">
        <el-input v-model="form.deviceName" />
      </el-form-item>
      <el-form-item :label="$t('deviceCore')">
        <el-input v-model="form.deviceCore" />
      </el-form-item>
      <el-form-item :label="$t('protocol')">
        <el-input v-model="form.protocol" />
      </el-form-item>
      <el-form-item :label="$t('suffix')">
        <el-input v-model="form.suffix" />
      </el-form-item>
      <el-form-item :label="$t('begin')">
        <el-input v-model="form.beginCore" />
      </el-form-item>
      <el-form-item :label="$t('end')">
        <el-input v-model="form.endCore" />
      </el-form-item>
      <el-form-item :label="$t('function')">
        <el-button type="primary" :disabled="disabled" @click="btnAdd" v-text="$t('add')" />
        <el-button type="primary" :disabled="disabled" @click="btnCopy" v-text="$t('save')" />
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="lists"
      style="width: 100%"
    >
      <el-table-column :label="$t('device')+$t('name')" >
        <template slot-scope="scope">
          <el-input v-model="scope.row.deviceName" clearable />
        </template>
      </el-table-column>
      <el-table-column :label="$t('protocol')" >
        <template slot-scope="scope">
          <el-input v-model="scope.row.protocol" disabled />
        </template>
      </el-table-column>
      <el-table-column :label="$t('deviceCore')" >
        <template slot-scope="scope">
          <el-input v-model="scope.row.deviceCore" clearable />
        </template>
      </el-table-column>
      <el-table-column prop="deviceServer" :label="$t('server')"  />
      <el-table-column prop="msg" :label="$t('message')" />
      <el-table-column :label="$t('function')" >
        <template slot-scope="scope">
          <el-button-group>
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="del(scope.row)"
            >{{ $t('delete') }}
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { listDeviceServer } from '@/api/iot/iotDeviceServerApi'
import {
  failureNotice,
  cancelNotice
} from '@/util/common'
import {
  registerDevice
} from '@/api/iot/iotDeviceApi'
import { getUserId } from '@/util/storage'

export default {
  name: 'CopyDevice',
  data() {
    return {
      lists: [],
      templateDeviceCore: null,
      templateDeviceName: null,
      form: {
        deviceName: null,
        protocol: null,
        deviceCore: null,
        beginCore: null,
        endCore: null,
        serverId: null,
        deviceServer: null
      },
      loading: false,
      userId: getUserId(),
      serverList: [],
      serverId: null,
      disabled: false
    }
  },
  mounted() {
    const param = this.$route.query
    this.templateDeviceCore = param.deviceCore
    if (!this.templateDeviceCore) {
      return
    } else {
      const templateDeviceCoreList = this.templateDeviceCore.split('')
      let deviceCore = ''
      let isNum = true
      for (let i = templateDeviceCoreList.length - 1, j = 0; i >= j; i--) {
        if (isNum && parseInt(templateDeviceCoreList[i])) {
          continue
        } else {
          isNum = false
        }
        deviceCore = templateDeviceCoreList[i] + deviceCore
      }
      this.form.deviceCore = deviceCore
    }
    this.templateDeviceName = param.deviceName
    this.serverId = parseInt(param.serverId)
    const templateDeviceNameList = this.templateDeviceName.split('')
    let deviceName = ''
    let isNum = true
    for (let i = templateDeviceNameList.length - 1, j = 0; i >= j; i--) {
      if (isNum && parseInt(templateDeviceNameList[i])) {
        continue
      } else {
        isNum = false
      }
      deviceName = templateDeviceNameList[i] + deviceName
    }
    this.form.deviceName = deviceName
    this.listDeviceServer()
    this.setTagsViewTitle()
  },
  methods: {
    registerDevice(i) {
      const that = this
      return new Promise(function(resolve, reject) {
        const deviceCore = that.lists[i].deviceCore
        registerDevice({
          ...that.lists[i],
          templateDeviceCore: that.templateDeviceCore,
          userId: that.userId
        }).then(res => {
          const { code, msg } = res
          for (let i = 0; i < that.lists.length; i++) {
            if (that.lists[i].deviceCore !== deviceCore) {
              continue
            }
            if (i === that.lists.length - 2) {
              that.loading = false
            }
            const result = {
              ...that.lists[i],
              msg: null,
              res: null
            }
            if (code === '200') {
              result.msg = that.$t('success')
            } else {
              result.msg = msg
            }
            that.lists.splice(i, 1, result)
          }
          resolve('成功')
        })
      })
    },
    test(i) {
      this.registerDevice(i).then(res => {
        if (i < this.lists.length) {
          this.test(i + 1)
        } else {
          this.disabled = false
        }
      })
    },
    listDeviceServer() {
      listDeviceServer(null).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.serverList = data
        }
      })
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.$t('copy')}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    btnAdd() {
      if (!this.form.beginCore || !this.form.endCore) {
        failureNotice(this, this.$t('begin') + '' + this.$t('end'))
        return
      }

      if (this.form.deviceName == null || this.form.deviceName === '') {
        failureNotice(this, this.$t('name'))
        return
      }
      if (this.form.deviceCore == null || this.form.deviceCore === '') {
        failureNotice(this, this.$t('deviceCore'))
        return
      }
      const beginCore = parseInt(this.form.beginCore)
      const endCore = parseInt(this.form.endCore)
      if (endCore < beginCore) {
        failureNotice(this, this.$t('begin') + '>' + this.$t('end'))
        return
      }

      for (let i = beginCore; i <= endCore; i++) {
        const deviceInfo = {}
        deviceInfo.deviceName = this.form.deviceName + i
        if (this.form.suffix && this.form.suffix !== '') {
          deviceInfo.deviceName = deviceInfo.deviceName + this.form.suffix
        }
        deviceInfo.deviceCore = this.form.deviceCore + i
        deviceInfo.serverId = this.serverId
        for (const deviceServer of this.serverList) {
          if (deviceServer.serverId === this.serverId) {
            deviceInfo.deviceServer = deviceServer.name
          }
        }
        deviceInfo.status = 10
        this.lists.push(deviceInfo)
      }
    },
    btnCopy() {
      const that = this
      this.$confirm(this.$t('begin'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          that.disabled = true
          that.test(0)
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    del(item) {
      const that = this
      this.$confirm(this.$t('delete'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          for (let i = 0; i < that.lists.length; i++) {
            if (item.deviceCore === that.lists[i].deviceCore) {
              that.lists.splice(i, 1)
            }
          }
        })
        .catch(function() {
          cancelNotice(that)
        })
    }
  }
}
</script>
